// src/stores/tags.ts
import { defineStore } from 'pinia'
import type { RouteLocationNormalized } from 'vue-router'

export interface TagView extends Partial<RouteLocationNormalized> {
  title?: string
  path: string
  name?: string | symbol
}

export const useTagsStore = defineStore('tags', {
  state: () => ({
    visitedViews: [] as TagView[],
    cachedViews: [] as (string | undefined)[]
  }),
  
  actions: {
    addView(view: RouteLocationNormalized) {
      this.addVisitedView(view)
      this.addCachedView(view)
    },
    
    addVisitedView(view: RouteLocationNormalized) {
      if(view.path=='//dashboard'){
        view.path='/dashboard'
      }

      // 避免重复添加
      if (this.visitedViews.some(v => v.path === view.path)) return
      
      this.visitedViews.push(
        Object.assign({}, view, {
            title: (view.meta?.title as string) || 'no-name'
        })
      )
    },
    
    addCachedView(view: RouteLocationNormalized) {
      if (this.cachedViews.includes(view.name as string)) return
      if (view.meta?.keepAlive) {
        this.cachedViews.push(view.name as string)
      }
    },
    
    delView(view: TagView) {
      return new Promise(resolve => {
        this.delVisitedView(view)
        this.delCachedView(view)
        resolve({
          visitedViews: [...this.visitedViews],
          cachedViews: [...this.cachedViews]
        })
      })
    },
    
    delVisitedView(view: TagView) {
      return new Promise(resolve => {
        for (const [i, v] of this.visitedViews.entries()) {
          if (v.path === view.path) {
            this.visitedViews.splice(i, 1)
            break
          }
        }
        resolve([...this.visitedViews])
      })
    },
    
    delCachedView(view: TagView) {
      return new Promise(resolve => {
        const index = this.cachedViews.indexOf(view.name as string)
        index > -1 && this.cachedViews.splice(index, 1)
        resolve([...this.cachedViews])
      })
    },
    
    delOthersViews(view: TagView) {
      return new Promise(resolve => {
        this.visitedViews = this.visitedViews.filter(v => {
          return v.meta?.affix || v.path === view.path
        })
        this.cachedViews = this.cachedViews.filter(item => {
          return item === view.name
        })
        resolve({
          visitedViews: [...this.visitedViews],
          cachedViews: [...this.cachedViews]
        })
      })
    },
    
    delAllViews() {
      return new Promise(resolve => {
        this.visitedViews = this.visitedViews.filter(tag => tag.meta?.affix)
        this.cachedViews = []
        resolve({
          visitedViews: [...this.visitedViews],
          cachedViews: [...this.cachedViews]
        })
      })
    },
    
    updateVisitedView(view: RouteLocationNormalized) {
      for (let v of this.visitedViews) {
        if (v.path === view.path) {
          v = Object.assign(v, view)
          break
        }
      }
    }
  }
})